<template>
  <div class="mapBox">
    <div id="sMap" class="map-select-wrap"></div>
    <div class="map-btn" v-show="MapClick">
      <el-button type="primary" @click.native="closeMapBtn">关闭</el-button>
    </div>
  </div>
</template>
<script>
import AMap from 'AMap'
import config from '../../../config'
let sMap
export default {
  name: 'mapSelect',
  props: ['LngLat', 'MapClick'],
  data () {
    return {
      sMap: null,
      mapStyle: config.mapStyle
    }
  },
  mounted () {
    sMap = new AMap.Map('sMap', { mapStyle: this.mapStyle })
    let point = new AMap.LngLat(this.LngLat.lng, this.LngLat.lat)
    sMap.setCenter(point)
    sMap.setZoom(19)

    let marker = new AMap.Marker({
      position: point,
      title: ''
    })
    sMap.add(marker)
    this.init()
  },
  watch: {
    LngLat: {
      handler (curVal) {
        this.init()
      },
      deep: true
    }
  },
  methods: {
    init () {
      const _this = this
      // 绑定地图事件
      sMap.on('click', function (e) {
        if (!_this.MapClick) {
          return
        }
        sMap.clearMap()
        let newPoint = new AMap.LngLat(e.lnglat.lng, e.lnglat.lat)
        let newMarker = new AMap.Marker({
          position: newPoint,
          title: ''
        })
        sMap.add(newMarker)
        _this.LngLat.lng = e.lnglat.lng
        _this.LngLat.lat = e.lnglat.lat
        _this.$store.commit('setPointData', _this.LngLat)
      })
    },
    closeMapBtn () {
      let _this = this
      _this.$store.commit('setPointPopShow', false)
    }
  }
}
</script>

<style>
.mapBox {
  width: 400px;
  height: 340px;
  position: relative;
}
.map-select-wrap {
  width: 400px;
  height: 300px;
}
.map-btn {
  text-align: center;
  padding: 10px 0;
}
</style>
